//
//  ForgetpasswordViewController.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/6/12.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "ForgetpasswordViewController.h"
#import "WKProgressHUD.h"
#import "TopBackView.h"
#import "Common.h"

@interface ForgetpasswordViewController ()<UITextFieldDelegate, TopBackViewDelegate>

@property (nonatomic, strong) UITextField *phoneTextField;

@property (nonatomic, strong) UITextField *captchaTextField;

@property (nonatomic, strong) UITextField *passwordField;

@property (nonatomic, strong) UIButton *captchaButton;

@property (nonatomic, assign) NSInteger secondCountDown;

@property (nonatomic, assign) NSInteger integer1;

@property (nonatomic, assign) NSInteger integer2;

@property (nonatomic, strong) WKProgressHUD *hud;

@property (nonatomic, strong) TopBackView *topBackView;

@end

@implementation ForgetpasswordViewController

- (TopBackView *)topBackView {
    if (!_topBackView) {
        _topBackView = [[TopBackView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 64) title:@"找回密码"];
        _topBackView.delegate = self;
        _topBackView.rightButton.hidden = YES;

    }
    return _topBackView;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    ///设置UI
    [self setUpUI];
    
    ///添加观察者
    [self observerManage];
}

- (void)setUpUI {
    [self.view addSubview:self.topBackView];
    
    self.view.backgroundColor = WhiteColor;
    
    ///布局子视图
    [self initSubViews];
}

- (void)initSubViews{
    
    UILabel *alertLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 64, screenWidth, 30)];
    alertLabel.text = @"请输入您手机号和短信验证码，并重新设置密码";
    alertLabel.textAlignment = NSTextAlignmentCenter;
    alertLabel.font = Font(12);
    alertLabel.backgroundColor = Color_RGB(234, 234, 234, 1);
    [self.view addSubview:alertLabel];
    
    self.phoneTextField = [[UITextField alloc]init];
    self.captchaTextField = [[UITextField alloc]init];
    self.passwordField = [[UITextField alloc]init];
    self.passwordField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    self.phoneTextField = [[UITextField alloc]init];
    self.phoneTextField.placeholder = @"请输入手机号";
    self.phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    self.captchaTextField = [[UITextField alloc]init];
    self.captchaTextField.placeholder = @"请输入验证码";
    self.captchaTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    
    self.passwordField = [[UITextField alloc]init];
    self.passwordField.placeholder = @"请输入6-14位密码";
    self.passwordField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    //手机号
    UIView *firstV = [self backViewWithFloat:CGRectGetMaxY(alertLabel.frame)
                                    andField:self.phoneTextField
                                    andImage:[UIImage imageNamed:@"register_phone"]];
    
    [self.view addSubview:firstV];
    
    //验证码
    UIView *secondV = [self backViewWithFloat:CGRectGetMaxY(firstV.frame)
                                     andField:self.captchaTextField
                                     andImage:[UIImage imageNamed:@"register_capture"]];
    
    [self.view addSubview:secondV];
    
    
    //密码
    UIView *thirdV = [self backViewWithFloat:CGRectGetMaxY(secondV.frame)
                                    andField:self.passwordField
                                    andImage:[UIImage imageNamed:@"register_password"]];
    
    [self.view addSubview:thirdV];
    
    
    //获取验证吗
    self.captchaButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    self.captchaButton.frame = CGRectMake(screenWidth - 100 * kWidth, (cellHeight - 23)/2.0, 75 * kWidth, 23 * kHeight);
    [self.captchaButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.captchaButton setTitleColor:YellowColor forState:UIControlStateNormal];
    [self.captchaButton setBackgroundColor:Color_RGB(253, 243, 232, 1)];
    
    [self.captchaButton addTarget:self
                           action:@selector(captchaButtonAction:)
                 forControlEvents:UIControlEventTouchUpInside];
    
    self.captchaButton.titleLabel.font = Font(12);
    self.captchaButton.layer.cornerRadius = 5;
    self.captchaButton.layer.borderColor = YellowColor.CGColor;
    self.captchaButton.layer.borderWidth = 0.5;
    
    [firstV addSubview:self.captchaButton];
    
    
    
    UIButton *agreeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    agreeButton.frame = CGRectMake(18 , CGRectGetMaxY(thirdV.frame) + 30 * kHeight, screenWidth - 36, 35 * kHeight);
    agreeButton.titleLabel.font = Font(15);
    agreeButton.backgroundColor = YellowColor;
    agreeButton.layer.cornerRadius = 5;
    [agreeButton setTitle:@"确 定" forState:UIControlStateNormal];
    [agreeButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    [self.view addSubview:agreeButton];
    [agreeButton addTarget:self action:@selector(confirmButton) forControlEvents:UIControlEventTouchUpInside];
    
    
}

- (UIView *)backViewWithFloat:(CGFloat)y
                     andField:(UITextField *)textField
                     andImage:(UIImage *)image {
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, y, screenWidth, cellHeight)];
    
    CGSize size = CGSizeMake(image.size.width, image.size.height);
    UIImageView *imaV = [[UIImageView alloc]initWithImage:image];
    imaV.frame = CGRectMake(28 * kWidth, (cellHeight - size.height)/2.0, size.width, size.height);
    [view addSubview:imaV];
    
    textField.frame = CGRectMake(CGRectGetMaxX(imaV.frame) + 17, 0, screenWidth - 100, view.frame.size.height);
    textField.font = Font(12);
    [view addSubview:textField];
    textField.delegate = self;
    textField.returnKeyType = UIReturnKeyDone;
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, view.frame.size.height - 0.5, screenWidth - 36, 0.5)];
    [view addSubview:label];
    label.backgroundColor = LineGrayColor;
    
    return  view;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}



#pragma mark -
#pragma mark - 提交, 确认提交信息
-(void)confirmButton {
   
    /// 1, 确认信息
    if (self.phoneTextField.text.length <= 0 ||
        self.captchaTextField.text.length <= 0 ||
        self.passwordField.text.length <= 0)
    {
        [WKProgressHUD popMessage:@"请将信息填写完整" inView:self.view duration:1.5 animated:YES];
        return;
    }

    NSDictionary *dic = @{@"phone" : self.phoneTextField.text,
                          @"password" : self.passwordField.text,
                          @"usertype" : userType,
                          @"authcode" : self.captchaTextField.text};


    __weak typeof(self) weakSelf = self;
    
 
   
    [[Common shared] afPostRequestWithUrlString:forgetpassword parms:dic finishedBlock:^(id responseObj) {
        
       
        
        NSDictionary *dictionry = [NSJSONSerialization JSONObjectWithData:responseObj
                                                                  options:NSJSONReadingMutableLeaves
                                                                    error:nil];
        
        if ([dictionry[@"success"] boolValue])
        {
            
            [WKProgressHUD popMessage:dictionry[@"message"]
                               inView:weakSelf.view
                             duration:1.5
                             animated:YES];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        }
        else
        {
            [WKProgressHUD popMessage:dictionry[@"message"]
                               inView:weakSelf.view
                             duration:1.5
                             animated:YES];

        }
    } failedBlock:^(NSString *errorMsg) {
        
        [WKProgressHUD dismissInView:weakSelf.view animated:YES];
        NSLog(@"%@",errorMsg);
    }];
}


#pragma mark -
#pragma mark - TopBackViewDelegate 协议
- (void)backViewPopViewController {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -
#pragma mark - 验证码方法
- (void)captchaButtonAction:(UIButton *)sender{
    
    //先判断手机号的正确
    
    NSString *regExp = @"^[1]([3][0-9]|[8][0-9]|[5][0-9]|45|47|76|77|78)[0-9]{8}$";
   
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regExp];
    
    BOOL isRight = [pred evaluateWithObject:self.phoneTextField.text];
    
    if (isRight) {
    
        NSString *urlString = [NSString stringWithFormat:@"%@login/resetcaptcha",Main_interface];
        
        NSDictionary *dic = @{@"phone":self.phoneTextField.text,
                              @"usertype":userType};
        
        __weak typeof(self) weakSelf = self;
        
   
        
        [[Common shared] afPostRequestWithUrlString:urlString parms:dic finishedBlock:^(id responseObj) {
            
           
            
            NSDictionary *diction = [NSJSONSerialization JSONObjectWithData:responseObj
                                                                    options:NSJSONReadingMutableLeaves
                                                                      error:nil];
            
            
            [WKProgressHUD popMessage:diction[@"message"] inView:weakSelf.view duration:1.5 animated:YES];
            
            if ([diction[@"success"] boolValue]) {
                
                [sender setTintColor:WhiteColor];
                sender.userInteractionEnabled = NO;
                _secondCountDown = 60;
                NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(timeFireAction:) userInfo:nil repeats:YES];
                [time fire];
            }

            
        } failedBlock:^(NSString *errorMsg) {
            
       
        }];
 

    } else {
        
        [WKProgressHUD popMessage:@"手机号码不正确，请重新输入" inView:self.view duration:1.5 animated:YES];
        
    }
    
}
- (void)timeFireAction:(NSTimer *)time{
    _secondCountDown --;
    
    //设置button下划线
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"(%zis)",_secondCountDown]];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSForegroundColorAttributeName value:YellowColor range:strRange];  //设置颜色
    [self.captchaButton setAttributedTitle:str forState:UIControlStateNormal];
    
    
    if (_secondCountDown <= 0) {
        [time invalidate];
        self.captchaButton.userInteractionEnabled = YES;
        //设置button下划线
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"重新发送"];
        NSRange strRange = {0,[str length]};
        [str addAttribute:NSForegroundColorAttributeName value:YellowColor range:strRange];  //设置颜色
        //        [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
        
        [self.captchaButton setAttributedTitle:str forState:UIControlStateNormal];
        
    }
}


#pragma mark -
#pragma mark - 添加观察者
- (void)observerManage {
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appGoForeground:)
                                                 name:AppIntoForeground
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(appGoBackground:)
                                                 name:AppIntoBackground
                                               object:nil];
}


#pragma mark -
#pragma mark - 执行观察到的通知
- (void)appGoBackground:(NSNotification *)notification{
    
    _integer1 = [notification.userInfo[@"time"] integerValue];
    
}
- (void)appGoForeground:(NSNotification *)notification{
    NSInteger integer = [notification.userInfo[@"time"] integerValue];
    
    _integer2 = (integer - _integer1)/1000;
    
    _secondCountDown = _secondCountDown - _integer2;
    
}


#pragma mark -
#pragma mark - 控制器销毁, 移除通知
- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:AppIntoForeground
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:AppIntoBackground
                                                  object:nil];
    
    NSLog(@"%s", __func__);
}



/**
    弃用的一些方法
    @param string
 */
- (void)showAlertWithString:(NSString *)string {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1   = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2   = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action1];
    [alert addAction:action2];
    
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

- (UIView *)backViewWithLabelString:(NSString *)string
                       andTextField:(UITextField *)field
                         andInteger:(NSInteger)integer {
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 104 + 40 * integer, screenWidth, 40)];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(14, 5, 130 * kWidth, 30)];
    label.text = string;
    label.font = Font(15);
    
    [view addSubview:label];
    
    
    field.frame = CGRectMake(CGRectGetMaxX(label.frame), 5, screenWidth - CGRectGetMaxX(label.frame) - 14, 30);
    field.delegate = self;
    field.font = Font(15);
    
    [view addSubview:field];
    
    UILabel *lineL = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetHeight(view.frame) - 0.5, screenWidth, 0.5)];
    lineL.backgroundColor = LineGrayColor;
    [view addSubview:lineL];
    
    
    return view;
}





@end
